package miaodi

import (
	"github.com/tealeg/xlsx"
	"github.com/PuerkitoBio/goquery"
	"fmt"
	"time"
	"io/ioutil"
)

var fileList []string

func addHeader(sheet *xlsx.Sheet, document *goquery.Document) {
	row := (*sheet).AddRow()

	document.Find("thead tr").Each(func(i int, selection *goquery.Selection) {
		length := selection.Find("th").Length()
		for i := 0; i < length; i++ {
			cell := row.AddCell()
			cell.Value = selection.Find("th").Eq(i).Text()
		}
	})
}

func addRowCell(sheet *xlsx.Sheet, li [][]string) {
	for i := 0; i < len(li); i++ {
		row := sheet.AddRow()
		for j := 0; j < len(li[i]); j++ {
			cell := row.AddCell()
			cell.Value = li[i][j]
			cell.FormattedValue()
		}
	}
}

func saveXlsx(file *xlsx.File, output string) string {
	now := time.Now()
	filename := fmt.Sprintf("%s-%d%d%d%d.xlsx", "miaodi", now.Year(), now.Month(), now.Day(), now.Hour())

	filePath := fmt.Sprintf("%s/%s", output, filename)
	file.Save(filePath)
	return filePath
}

func listAll(path string) {
	files, _ := ioutil.ReadDir(path)
	for _, file := range files {
		if file.IsDir() {
			continue
		}
		fileList = append(fileList, file.Name())
	}
	fmt.Printf("扫描目录 %s 成功,共 %d 个文件.\n\n", path, len(fileList))
}

func currentTime() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

func CreateXlsx(path string, output string) {
	fmt.Println(currentTime())
	listAll(path)

	var info [][]string

	for _, name := range fileList {
		fileName := path + "/" + name
		f := LoadFile(fileName)
		defer f.Close()
		doc := QueryHtml(f)
		str := ParseHtml(doc)
		info = append(info, str...)
		fmt.Printf("文件 %s 读取完成,共 %d 条记录\n", name, len(str))
	}
	fmt.Printf("目录扫描完成,共 %d 条数据\n", len(info))

	xl := xlsx.NewFile()
	sheet, _ := xl.AddSheet("Sheet1")

	headers := make([][]string, 1)
	headers[0] = Header
	addRowCell(sheet, headers)
	addRowCell(sheet, info)
	filename := saveXlsx(xl, output)
	fmt.Printf("\n生成excel文件成功,文件名: %s\n", filename)
	fmt.Println(currentTime())
}
